// mainwindow.cpp
#include "gamewidget.h"

GameWidget::GameWidget(QWidget *parent) : QWidget(parent) {
    setFixedSize(WIDTH, HEIGHT);
    setFocusPolicy(Qt::StrongFocus);

    timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this, &GameWidget::gameLoop);

    initGame();
    timer->start(200); // 200ms 刷新间隔
}

void GameWidget::initGame() {
    snake.length = 3;
    snake.x[0] = WIDTH / 2;
    snake.y[0] = HEIGHT / 2;
    snake.dir = RIGHT;

    for (int i = 1; i < snake.length; ++i) {
        snake.x[i] = snake.x[i-1] - BLOCK_SIZE;
        snake.y[i] = snake.y[i-1];
    }

    spawnFood();
    score = 0;
}

void GameWidget::spawnFood() {
    bool onSnake;
    do {
        onSnake = false;
        foodX = QRandomGenerator::global()->bounded(WIDTH / BLOCK_SIZE) * BLOCK_SIZE;
        foodY = QRandomGenerator::global()->bounded(HEIGHT / BLOCK_SIZE) * BLOCK_SIZE;

        // 检查食物是否与蛇身重叠
        for (int i = 0; i < snake.length; ++i) {
            if (foodX == snake.x[i] && foodY == snake.y[i]) {
                onSnake = true;
                break;
            }
        }
    } while (onSnake); // 如果重叠，重新生成
}

void GameWidget::paintEvent(QPaintEvent *) {
    QPainter painter(this);

    // 绘制背景
    painter.fillRect(0, 0, width(), height(), Qt::black);

    // 绘制蛇
    for (int i = 0; i < snake.length; ++i) {
        painter.setBrush(i == 0 ? Qt::yellow : Qt::green);
        painter.drawRect(snake.x[i], snake.y[i], BLOCK_SIZE, BLOCK_SIZE);
    }

    // 绘制食物
    painter.setBrush(Qt::red);
    painter.drawRect(foodX, foodY, BLOCK_SIZE, BLOCK_SIZE);

    // 绘制得分
    painter.setPen(Qt::white);
    painter.setFont(QFont("Arial", 14));
    painter.drawText(10, 20, QString("Score: %1").arg(score));
}

void GameWidget::keyPressEvent(QKeyEvent *event) {
    switch (event->key()) {
    case Qt::Key_Up:
        if (snake.dir != DOWN) snake.dir = UP;
        break;
    case Qt::Key_Down:
        if (snake.dir != UP) snake.dir = DOWN;
        break;
    case Qt::Key_Left:
        if (snake.dir != RIGHT) snake.dir = LEFT;
        break;
    case Qt::Key_Right:
        if (snake.dir != LEFT) snake.dir = RIGHT;
        break;
    case Qt::Key_Escape:
        qApp->quit();
        break;
    }
}

void GameWidget::moveSnake() {
    // 移动身体
    for (int i = snake.length-1; i > 0; --i) {
        snake.x[i] = snake.x[i-1];
        snake.y[i] = snake.y[i-1];
    }

    // 移动头部
    switch (snake.dir) {
    case UP:    snake.y[0] -= BLOCK_SIZE; break;
    case DOWN:  snake.y[0] += BLOCK_SIZE; break;
    case LEFT:  snake.x[0] -= BLOCK_SIZE; break;
    case RIGHT: snake.x[0] += BLOCK_SIZE; break;
    default: break;
    }

    // 边界检测（穿墙）
    if (snake.x[0] >= WIDTH) snake.x[0] = 0;
    if (snake.x[0] < 0) snake.x[0] = WIDTH - BLOCK_SIZE;
    if (snake.y[0] >= HEIGHT) snake.y[0] = 0;
    if (snake.y[0] < 0) snake.y[0] = HEIGHT - BLOCK_SIZE;
}

void GameWidget::checkCollision() {
    // 食物碰撞

    if (snake.x[0] == foodX && snake.y[0] == foodY) {
        snake.length++;
        score += 10;
        spawnFood();
    }


    // 自碰撞
    for (int i = 1; i < snake.length; ++i) {
        if (snake.x[0] == snake.x[i] && snake.y[0] == snake.y[i]) {
            QMessageBox::information(this, "Game Over",
                                     QString("Score: %1").arg(score));
            initGame();
            break;
        }
    }
}

void GameWidget::gameLoop() {
    moveSnake();
    checkCollision();
    update(); // 触发重绘
}
